package net;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天的客户端对象
 */
public class ChatClient {
    private Socket socket;
    public ChatClient(){
        try {
            System.out.println("客户端启动...");
            socket = new Socket("127.0.0.1", 8088);
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }
    public void start(){
        try {
            //1.获取输出流对象，能够一次写一行
            PrintWriter pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream(), StandardCharsets.UTF_8)), true);
            //2.写数据
            Scanner sc=new Scanner(System.in);
            System.out.println("请输入数据:");
            while(true) {
                String content=sc.nextLine();
                if("exit".equalsIgnoreCase(content))break;
                pw.println(content);
            }
        }catch (IOException e){
            e.printStackTrace();
        } finally  {
            if (socket != null)
                try {socket.close();}catch (IOException e){e.printStackTrace();}//3.释放资源
        }
    }
    public static void main(String[] args) {
        new ChatClient().start();
    }
}
